//
//  PPNearbyShopViewController.m
//  pet
//
//  Created by 陈无忌 on 11/14/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPNearbyShopViewController.h"
#import "PPNearbyShopTableViewCell.h"

#import <AKLocationManager/AKLocationManager.h>
#import <CommonCrypto/CommonDigest.h>

#import "PPSystemConfiguraton.h"
#import "supportingHeadFiles.h"
#import "PPCustomBGTableView.h"

#import "PPUserAnnotation.h"
#import "PPShopAnnotation.h"

static NSString *APPKKEY = @"712274683";
static NSString *APPSERCE = @"4c167fee1b9a4125833f9b1d583a04c6";


@interface PPNearbyShopViewController ()<CLLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) PPUserAnnotation *userAnnotation;
@property (strong, nonatomic) NSMutableArray *shopArray;//附近用户列表
@property (strong, nonatomic) NSMutableArray *shopLocationArray;//附近用户坐标集
@property (strong, nonatomic) CLLocationManager *locationManager;

@property (weak, nonatomic) PPSystemConfiguraton *config;
@property (nonatomic) BOOL canReSetCenter;

@property (weak, nonatomic) IBOutlet PPCustomBGTableView *nearbyTableView;
@property (weak, nonatomic) IBOutlet UIButton *showMapButton;
@property (weak, nonatomic) IBOutlet UIButton *showListButton;

@end

@implementation PPNearbyShopViewController

-(PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (NSMutableArray *)shopArray
{
    if (!_shopArray) {
        _shopArray = [NSMutableArray array];
    }
    return _shopArray;
}

- (NSMutableArray *)userLocationArray
{
    if (!_shopLocationArray) {
        _shopLocationArray = [NSMutableArray array];
    }
    return _shopLocationArray;
}

-(void)viewWillAppear:(BOOL)animated
{
    [_mapView viewWillAppear];
    _mapView.delegate = self;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [_mapView viewWillDisappear];
    //    [[NSNotificationCenter defaultCenter] removeObserver:self];
    _mapView.delegate = nil;
}

- (void)alertShow:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
    [alert show];
}


- (void)showMap
{
    [self.showMapButton setSelected:YES];
    [self.showListButton setSelected:NO];
    [self.showMapButton setEnabled:NO];
    [self.showListButton setEnabled:YES];
    //table view hide
    [UIView animateWithDuration:0.35 animations:^(void){
        self.nearbyTableView.frame = CGRectMake(320, 44, self.view.frame.size.width, self.view.frame.size.height - 44);
    }completion:^(BOOL completed){
        //        [self.IHFunTableView reloadData];
    }];
}

- (void)showList
{
    [self.showMapButton setSelected:NO];
    [self.showListButton setSelected:YES];
    [self.showListButton setEnabled:NO];
    [self.showMapButton setEnabled:YES];
    //table view show
    [UIView animateWithDuration:0.35 animations:^(void){
        self.nearbyTableView.frame = CGRectMake(0, 44, self.view.bounds.size.width, self.view.bounds.size.height - 44);
        //        self.groupView.frame = CGRectMake(0, 564, 100, 370);
    }completion:^(BOOL completed){
        //        [self.nearbyTableView reloadData];
    }];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.nearbyTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.nearbyTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.nearbyTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.nearbyTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //table view
    self.nearbyTableView.delegate = self;
    self.nearbyTableView.dataSource = self;
    self.nearbyTableView.frame = CGRectMake(320, 44, self.view.frame.size.width, self.view.frame.size.height - 44);
    //button
    [self.showMapButton addTarget:self action:@selector(showMap) forControlEvents:UIControlEventTouchUpInside];
    [self.showListButton addTarget:self action:@selector(showList) forControlEvents:UIControlEventTouchUpInside];
    [self showMap];
    //location
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [self.locationManager requestAlwaysAuthorization];
    }
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"Requesting when in use auth");
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [self.locationManager requestAlwaysAuthorization];
        }
    }else if (status == kCLAuthorizationStatusRestricted) {
        NSLog(@"Location services Restricted");
        [self alertShow:@"定位服务被限制！"];
        // Alert the user and send them to the settings to turn on location
    }else if (status == kCLAuthorizationStatusDenied) {
        NSLog(@"Location services Denied");
        [self alertShow:@"定位服务被拒绝！"];
        // Alert the user and send them to the settings to turn on location
    }
    _mapView.showsUserLocation = YES;//显示定位图层
    _mapView.delegate = self;
    //set zoom
    for (int i = 0; i < 5; i++) {
        [_mapView zoomIn];
    }
    self.canReSetCenter = YES;
    [self setLocation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)findself:(id)sender {
    [_mapView removeAnnotations:self.shopLocationArray];
    [_mapView removeAnnotation:self.userAnnotation];
    for (int i = 0; i < 5; i++) {
        [_mapView zoomIn];
    }
    self.canReSetCenter = YES;
    [self setLocation];
}

- (void)setLocation
{
    [HUD showUIBlockingIndicatorWithText:@"正在定位"];
    [AKLocationManager startLocatingWithUpdateBlock:^(CLLocation *location) {
        self.config.locationPosLatitude = location.coordinate.latitude;
        self.config.locationPosLongitude = location.coordinate.longitude;
        [self setAnnation];
    } failedBlock:^(NSError *error) {
        NSLog(@"fail");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [HUD hideUIBlockingIndicator];
        });
    }];
}

- (void)setAnnation
{
    CLLocationCoordinate2D userLocation = CLLocationCoordinate2DMake(self.config.locationPosLatitude,  self.config.locationPosLongitude);
    NSDictionary *userCoordDict = BMKConvertBaiduCoorFrom(userLocation, BMK_COORDTYPE_GPS);
    userLocation = BMKCoorDictionaryDecode(userCoordDict);
    self.userAnnotation = [PPUserAnnotation annotationForPetShop:self.config.userInfo];
    [_mapView addAnnotation:self.userAnnotation];
    [_mapView setCenterCoordinate:self.userAnnotation.coordinate animated:YES];
    //shop
    [self shopGet];
    
}

//get shopLocation
-(void)shopGet
{
    [self.shopArray removeAllObjects];
    [self.shopLocationArray removeAllObjects];
    
    double centerLat;
    double centerLng;
    if (self.canReSetCenter) {
        centerLat = self.config.locationPosLatitude;
        centerLng = self.config.locationPosLongitude;
    }else{
        centerLat = _mapView.centerCoordinate.latitude;
        centerLng = _mapView.centerCoordinate.longitude;
    }
    NSString *url = [PPAPIList getAPIList].dianpingUrl;
    NSMutableDictionary *params =[[NSMutableDictionary alloc] initWithDictionary:@{
                                                                                   @"category":@"宠物",
                                                                                   @"radius":@5000,
                                                                                   @"latitude":@(centerLat),
                                                                                   @"longitude":@(centerLng),
                                                                                   @"sort":@1,
                                                                                   @"limit":@20,
                                                                                   @"platform":@2
                                                                                   }];
    NSString *sign = [self getSign:params];
    [params setObject:sign forKey:@"sign"];
    [params setObject:APPKKEY forKey:@"appkey"];
    [httpRequst GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSArray *businessesArray = responseObject[@"businesses"];
        NSError *err = nil;
        self.shopArray = [PPShop arrayOfModelsFromDictionaries:businessesArray error:&err];
        for (PPShop *shop in self.shopArray) {
            CLLocationCoordinate2D shopLocation = CLLocationCoordinate2DMake(shop.latitude,  shop.longitude);
            NSDictionary *shopCoordDict = BMKConvertBaiduCoorFrom(shopLocation, BMK_COORDTYPE_COMMON);
            shopLocation = BMKCoorDictionaryDecode(shopCoordDict);
            PPShopAnnotation *shopL = [PPShopAnnotation annotationForPetShop:shop];
            [_mapView addAnnotation:shopL];
            [self.shopLocationArray addObject:shopL];
        }
        [self.nearbyTableView reloadData];
        [HUD hideUIBlockingIndicator];
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        [self alertShow:@"数据获取失败！"];
        [HUD hideUIBlockingIndicator];
    }];
}

-(NSString *)getSign:(NSMutableDictionary *)dic
{
    NSMutableString *signString = [NSMutableString stringWithString:APPKKEY];
    NSMutableArray *array = [[NSMutableArray alloc] init];
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
    NSArray *sortedKeys = [dic allKeys];
    for (NSString *keyStr in sortedKeys) {
        NSDictionary *dic = @{@"keyStr":keyStr};
        [array addObject:dic];
    }
    NSSortDescriptor *distanceDescriptor = [[NSSortDescriptor alloc] initWithKey:@"keyStr" ascending:YES];
    NSArray *descriptors = [NSArray arrayWithObjects:distanceDescriptor,nil];
    [array sortUsingDescriptors:descriptors];
    
    for (NSDictionary *dic in array) {
        NSString *str = dic[@"keyStr"];
        [keyArray addObject:str];
    }
    for (NSString *key in keyArray) {
        [signString appendFormat:@"%@%@", key, [dic objectForKey:key]];
    }
    [signString appendString:APPSERCE];
    unsigned char digest[CC_SHA1_DIGEST_LENGTH];
    NSData *stringBytes = [signString dataUsingEncoding: NSUTF8StringEncoding];
    if (CC_SHA1([stringBytes bytes], [stringBytes length], digest)) {
        /* SHA-1 hash has been calculated and stored in 'digest'. */
        NSMutableString *digestString = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH];
        for (int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
            unsigned char aChar = digest[i];
            [digestString appendFormat:@"%02X", aChar];
        }
        return [digestString uppercaseString];
        
    } else {
        return nil;
    }
}


#pragma mark - Mapview Delegate

- (void)mapView:(BMKMapView *) mapView regionDidChangeAnimated:(BOOL) animated
{
    NSLog(@"end drag!");
    self.canReSetCenter = NO;
    [self shopGet];
}

-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    BMKPinAnnotationView *newAnnotationView = nil;
    if ([annotation isKindOfClass:[PPUserAnnotation class]]){
        newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.image = [UIImage imageNamed:@"heartPin"];
        newAnnotationView.animatesDrop = NO;
        return newAnnotationView;
    }else{
        newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.image = [UIImage imageNamed:@"shopPin"];
        newAnnotationView.animatesDrop = NO;
        return newAnnotationView;
    }
    return newAnnotationView;
}

#pragma mark - UITableView datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shopArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPNearbyShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nearbyShopCell"];
    PPShop *shop = [self.shopArray objectAtIndex:indexPath.row];
    [cell.shopAvatar setImageWithURL:[NSURL URLWithString:shop.s_photo_url] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    cell.shopNameLabel.text = shop.name;
    cell.shopAdressLabel.text = shop.address;
    cell.shopTeleLabel.text = [NSString stringWithFormat:@"电话：%@",shop.telephone];
    return cell;
}

#pragma mark -UITableView delegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
